//
//  ZLPUserViewController.m
//  TangYi
//
//  Created by dllo on 15/10/27.
//  Copyright (c) 2015年 赵连鹏. All rights reserved.
//

#import "ZLPUserViewController.h"
#import "ZLPUserTableViewCell.h"
#import "ZLPCollectionViewController.h"
#import "UMSocial.h"
#import <MessageUI/MessageUI.h>
#import "ZLPIsLoginHandle.h"
#import <UIImageView+WebCache.h>
#import "ZLPTakePhoto.h"
#import "ZLPAboutUsViewController.h"


@interface ZLPUserViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, MFMailComposeViewControllerDelegate>


@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) NSArray *picArr;
@property(nonatomic, retain) NSArray *nameArr;
@property(nonatomic, retain) NSArray *adviceArr;
@property(nonatomic, retain) NSArray *adviceText;
@property(nonatomic, retain) UIAlertView *alert;
@property(nonatomic, retain) UIView *headView;
@property(nonatomic, retain) UIImageView *iconImage;
@property(nonatomic, retain) UILabel *userNameLabel;
@property(nonatomic, copy) NSString *version;

@end

@implementation ZLPUserViewController

- (void)dealloc {
    
    [_version release];
    [_headView release];
    [_iconImage release];
    [_userNameLabel release];
    [_alert release];
    [_adviceArr release];
    [_adviceText release];
    [_picArr release];
    [_nameArr release];
    [_tableView release];
    [super dealloc];
}

- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"个人中心";
    
    [self createTableView];
    self.picArr = @[@"like.png", @"share.png"];
    self.nameArr = @[@"我的收藏", @"一键分享"];
    self.adviceArr = @[@"we.png", @"advice.png", @"banben.png"];
    self.adviceText = @[@"关于我们", @"意见反馈", @"版本检测"];
    
//    [self createHeadView];
//    [self createIconImageView];
//    [self createUserNameLabel];
    
}


- (void)createHeadView {
    
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 80)];
    self.tableView.tableHeaderView = self.headView;
    self.headView.backgroundColor = [UIColor whiteColor];
    [_headView release];
    
}

- (void)createIconImageView {
    self.iconImage = [[UIImageView alloc] init];
    [self.headView addSubview:self.iconImage];
    [_iconImage release];
    self.iconImage.layer.cornerRadius = 35;
    self.iconImage.layer.masksToBounds = YES;
    
    if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin) {
        [self.iconImage sd_setImageWithURL:[NSURL URLWithString:[ZLPIsLoginHandle shareZLPIsLoginHandle].picStr]];
    } else {
        self.iconImage.image = [UIImage imageNamed:@"login2x.png"];
    }
    self.iconImage.frame = CGRectMake(WIDTH / 2 - 35, 5, 70, 70);
    self.iconImage.userInteractionEnabled = YES;
    
    [self addGesture];
}

- (void)addGesture {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changePic:)];
    [self.iconImage addGestureRecognizer:tapGesture];
    [tapGesture release];
}

- (void)changePic:(UILongPressGestureRecognizer *)longGesture {
    if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin) {
        [ZLPTakePhoto sharePicture:^(UIImage *image) {
            
            self.iconImage.image = image;
            
        }];
    } else {
        NSLog(@"2222222222");
    }
}

- (void)createUserNameLabel {
    self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 25, WIDTH - 10, 30)];
    [self.headView addSubview:self.userNameLabel];
    [_userNameLabel release];
}

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -35, WIDTH, HEIGHT - 26) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    
}

#pragma mark tableView的的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    } else if (section == 1) {
        return 3;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    ZLPUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[ZLPUserTableViewCell alloc] init];
    }
    if (indexPath.section == 0) {
        cell.picImageView.image = [UIImage imageNamed:self.picArr[indexPath.row]];
        cell.nameLabel.text = self.nameArr[indexPath.row];
    } else if (indexPath.section == 1) {
        cell.picImageView.image = [UIImage imageNamed:self.adviceArr[indexPath.row]];
        cell.nameLabel.text = self.adviceText[indexPath.row];
    } else if (indexPath.section == 2) {
        cell.picImageView.image = [UIImage imageNamed:@"huancun.png"];
        cell.nameLabel.text = @"清除缓存";
        
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"%@", cachePath);
        CGFloat cacheSize = [self folderSizeAtPath:cachePath];
        NSLog(@"%g", cacheSize);
        cell.RAMLabel.text = [NSString stringWithFormat:@"%.2fM", cacheSize];
    } else if (indexPath.section == 3) {
        cell.picImageView.image = [UIImage imageNamed:@"night.png"];
        cell.nameLabel.text = @"夜间模式";
    } else if (indexPath.section == 4) {
        cell.picImageView.image = [UIImage imageNamed:@"logout.png"];
        cell.nameLabel.text = @"退出登陆";
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        NSLog(@"收藏");
        
//        if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin) {
            ZLPCollectionViewController *collectVC = [[ZLPCollectionViewController alloc] init];
            [self.navigationController pushViewController:collectVC animated:YES];
//        } else {
//            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请先登陆" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
//            
//        }
        
    } else if (indexPath.section == 0 && indexPath.row == 1) {
        NSLog(@"share");
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"563814b567e58efbc7003c2c"
                                          shareText:@"我发现了一个好用的app!@糖衣"
                                         shareImage:[UIImage imageNamed:@"appStore.png"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, nil]
                                           delegate:nil];
        
//    } else if (indexPath.section == 0 && indexPath.row == 0){
//        
//        // 快捷登陆
//        
//        if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin == NO) {
//            
//            
//            UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
//            
//            snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
//                
//                //          获取微博用户名、uid、token等
//                
//                if (response.responseCode == UMSResponseCodeSuccess) {
//                    
//                    UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
//                    
//                    NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
//                    NSLog(@"%@", response.data);
//                    
//                    NSLog(@"platform  %@", response.data[@"platform_error"]);
//                    
//                    [self.iconImage sd_setImageWithURL:[NSURL URLWithString:snsAccount.iconURL]];
//                    
//                    [ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin = YES;
//                    
//
//                    [ZLPIsLoginHandle shareZLPIsLoginHandle].userID = snsAccount.usid;
//                    NSLog(@"~~%@", [ZLPIsLoginHandle shareZLPIsLoginHandle].userID);
//                    
//                    
//                }});
//            
//        } else {
//            [self.iconImage sd_setImageWithURL:[NSURL URLWithString:[ZLPIsLoginHandle shareZLPIsLoginHandle].picStr]];
//        }
        
        
    }
    
    // 意见反馈
    if (indexPath.section == 1 && indexPath.row == 1) {
        NSLog(@"反馈");
        
        Class mailClass = NSClassFromString(@"MFMailComposeViewController");
        if (mailClass) {
            if ([mailClass canSendMail]) {
                [self displayMailBox];
            } else{
                [self showMailBoxOnDevice];
            }
        } else {
            [self showMailBoxOnDevice];
        }

        
    }
    // 版本检测
    if (indexPath.section == 1 && indexPath.row == 2) {
        NSLog(@"版本检测");
        
        self.version = [self getCurrentLocalVersion];
        NSLog(@"version: %@", self.version);
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"当前本版 :%@", self.version] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }
    // 关于我们
    if (indexPath.section == 1 && indexPath.row == 0) {
        
        ZLPAboutUsViewController *aboutVC = [[ZLPAboutUsViewController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
        self.version = [self getCurrentLocalVersion];
        aboutVC.version = self.version;
        
    }
    
    // 清除缓存
    if (indexPath.section == 2) {
        NSLog(@"清除缓存");
        
        if (indexPath.row == 0) {
            
            
            
            NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
            NSLog(@"手机系统版本: %@", phoneVersion);
            NSLog(@"%ld", (long)phoneVersion.integerValue);
            
            if (phoneVersion.integerValue >= 8) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要清除缓存吗?" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
                    NSString *sandBoxPath = [sandBox lastObject];
                    [self clearCache:sandBoxPath];
                    
                    [self.tableView reloadData];
                    
                }];
                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                    [self.tableView reloadData];
                }];
                
                [alert addAction:action1];
                [alert addAction:action2];
                
                [self presentViewController:alert animated:YES completion:^{
//                    [self.tableView reloadData];
                }];
                
            } else {
                
                UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要清除缓存吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alertV show];
                [alertV release];
//                [self.tableView reloadData];
            }
            
            
        }
    }
    
    
    // 夜间模式
    if (indexPath.section == 3) {

        
        if (self.view.window.alpha == 1) {
            self.view.window.alpha = 0.5;
        } else {
            self.view.window.alpha = 1;
        }
        
    }
    // 退出
//    if (indexPath.section == 4) {
//        if ([ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin) {
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出登陆" message:@"退出" preferredStyle:UIAlertControllerStyleActionSheet];
//            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                
//                
//            }];
//            
//            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//                
//                
//                [self getRidOfAuthorize];
//                
//                [ZLPIsLoginHandle shareZLPIsLoginHandle].isLogin = NO;
//                [ZLPIsLoginHandle shareZLPIsLoginHandle].picStr = nil;
//                self.iconImage.image = [UIImage imageNamed:@"login2x.png"];
//                [self.tableView reloadData];
//                
//            }];
//            
//            [alert addAction:cancleAction];
//            [alert addAction:sureAction];
//            [self presentViewController:alert animated:YES completion:nil];
//        } else {
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请先登陆" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//            
//            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//                
//                
//            }];
//            
//            [alert addAction:sureAction];
//            [self presentViewController:alert animated:YES completion:nil];
//        }
//    }
}

#pragma mark - 解除授权的方法
//- (void)getRidOfAuthorize {
//    
//    [[UMSocialDataService defaultDataService] requestUnOauthWithType:UMShareToSina completion:^(UMSocialResponseEntity *response) {
//
//        NSLog(@"~~%@", response);
//        NSLog(@"platform  %@", response.data[@"platform_error"]);
//     
//    }];
//    
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 5;
    }
}

#pragma mark - 获取当前app版本
- (NSString *)getCurrentLocalVersion
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
    return appVersion;
}

#pragma mark - 用户反馈
- (void)sendEmail:(UIButton *)button {
    Class mailClass = NSClassFromString(@"MFMailComposeViewController");
    if (mailClass) {
        if ([mailClass canSendMail]) {
            [self displayMailBox];
        } else{
            [self showMailBoxOnDevice];
        }
    } else {
        [self showMailBoxOnDevice];
    }
}

// 打开设备自带的邮箱工具
- (void)showMailBoxOnDevice {
    NSString *mail = @"835959766@qq.com";
    mail = [mail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mail]];
}


- (void)displayMailBox {
    MFMailComposeViewController *mailBox = [[MFMailComposeViewController alloc] init];
    NSArray *recipient = [NSArray arrayWithObjects:@"835959766@qq.com", nil];
    [mailBox setToRecipients:recipient];
    [mailBox setSubject:@"意见反馈"];
    NSString *message = @"请输入您的意见或看法,感谢您的反馈,我们会及时处理的.\n";
    [mailBox setMessageBody:message isHTML:YES];
//    UIImage *image = [UIImage imageNamed:@"saber.jpeg"];
//    NSData *data = UIImagePNGRepresentation(image);
//    [mailBox addAttachmentData:data mimeType:@"" fileName:@""];
    mailBox.mailComposeDelegate = self;
    
    [self presentViewController:mailBox animated:YES completion:^{
        
        
        
    }];
    
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    NSString *message;
    switch (result) {
        case MFMailComposeResultCancelled:
            message = @"取消发送";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultSaved:
            message = @"保存草稿";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultSent:
            message = @"已发送";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultFailed:
            message = @"发送失败";
            NSLog(@"%@", message);
            break;
            
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}



#pragma mark - 计算缓存的大小
- (float )folderSizeAtPath:(NSString *)folderPath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]){
        return 0;
    } else {
        NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
        NSString *fileName;
        long long folderSize = 0;
        while ((fileName = [childFilesEnumerator nextObject]) != nil){
            NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        return folderSize / 1024 / 1024.0;
    }
    
}

- (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    if (buttonIndex == 0 && alertView == self.alert) {
//        NSLog(@"确定");
//        
//        NSFileManager *manager = [NSFileManager defaultManager];
//        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//        NSLog(@"%@", cachePath);
//        CGFloat cacheSize = [self folderSizeAtPath:cachePath];
//        BOOL result = [manager removeItemAtPath:cachePath error:nil];
//        if (result) {
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@%.2fM", @"清除成功!共", cacheSize] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
//            
//            [self.tableView reloadData];
//            
//        } else {
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"清除失败"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
//        }
//
//        
//    } else if (buttonIndex == 1) {
//        NSLog(@"取消");
////        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"清除失败"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
////        [alert show];
//    }
//}


- (void)clearCache:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
